<template>
  <div>
    <span>
      人员信息
    </span>
    <el-divider/>
    <el-form :model="userInfoFormValue" v-loading="userLoading" class="form-inline" label-width="100">
      <div style="display: flex;">
        <el-form-item label="部门" style="flex: 1; margin-right: 20px;">
          <el-input :disabled="true" v-model="userInfoFormValue.deptName"/>
        </el-form-item>
        <el-form-item label="姓名" style="flex: 1; margin-right: 20px;">
          <el-input :disabled="true" v-model="userInfoFormValue.userName"/>
        </el-form-item>
        <el-form-item label="身份证号" style="flex: 1; margin-right: 20px;">
          <el-input :disabled="true" v-model="userInfoFormValue.userIdNumber"/>
        </el-form-item>
        <el-form-item label="工号" style="flex: 1; margin-right: 20px;">
          <el-input :disabled="true" v-model="userInfoFormValue.jobNumber"/>
        </el-form-item>
      </div>
      <div style="display: flex;">
        <el-form-item label="性别" style="flex: 1; margin-right: 20px;">
          <el-input :disabled="true" v-model="userInfoFormValue.userSex"/>
        </el-form-item>
        <el-form-item label="身份类别" style="flex: 1; margin-right: 20px;">
          <el-input :disabled="true" v-model="userInfoFormValue.userCategory"/>
        </el-form-item>
        <el-form-item label="最高学历" style="flex: 1; margin-right: 20px;">
          <el-input :disabled="true" v-model="userInfoFormValue.highestEducation"/>
        </el-form-item>
        <el-form-item label="毕业时间" style="flex: 1; margin-right: 20px;">
          <el-input :disabled="true" v-model="userInfoFormValue.graduationTime"/>
        </el-form-item>
      </div>
    </el-form>
    <span>
      已签约协议
      <el-button type="primary" @click="handAdd">新增</el-button>
    </span>
    <el-divider/>
    <el-table :data="tableData" v-loading="tableLoading" stripe style="width: 100%; height: 80%">
      <el-table-column prop="agreementName" label="名称"/>
      <el-table-column prop="agreementTypeName" label="类型"/>
      <el-table-column prop="agreementSignDate" label="签订时间"/>
      <el-table-column prop="agreementStartDate" label="开始时间"/>
      <el-table-column prop="agreementEndDate" label="结束时间"/>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button size="small" @click="handleDetail(scope.$index, scope.row)">
            详情
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="agreementDialogVisible" title="合同协议" width="1000">
      <el-form :model="agreementValue" ref="agreementFormRef" :rules="agreementValueRules" v-loading="dialogLoading" label-width="auto">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同类别" prop="agreementTypeId" style="flex: 1; margin-right: 10px;">
              <el-select :disabled = "isDisabled"
                         v-model="agreementValue.agreementTypeId"
                         placeholder="选择类别"
                         @change="agreementTypeChange()"
              >
                <el-option
                    v-for="item in agreementTypeList"
                    :key="item.id"
                    :label="item.typeName"
                    :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="合同名称" prop="agreementName" style="flex: 1; margin-right: 10px;">
              <el-input :disabled = "isDisabled" v-model="agreementValue.agreementName"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="签署时间" prop="agreementSignDate" style="flex: 1; margin-right: 10px;">
              <el-date-picker :disabled = "isDisabled" v-model="agreementValue.agreementSignDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="生效时间" prop="agreementStartDate" style="flex: 1; margin-right: 10px;">
              <el-date-picker :disabled = "isDisabled" v-model="agreementValue.agreementStartDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="失效时间" prop="agreementEndDate" style="flex: 1; margin-right: 10px;">
              <el-date-picker :disabled = "isDisabled" v-model="agreementValue.agreementEndDate"
                              type="date"
                              value-format="YYYY-MM-DD"
                              style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row v-for="item in agreementAttributeList">
          <el-col :span="8">
            <el-form-item :label="item.attributeName" style="flex: 1; margin-right: 10px;">
              <el-input :disabled = "isDisabled" v-if="item.attributeType === 1" v-model="item.attributeValue"/>
              <el-input :disabled = "isDisabled" type="number"  v-else-if="item.attributeType === 2" v-model="item.attributeValue"/>
              <el-input :disabled = "isDisabled" type="number"  v-else-if="item.attributeType === 3" v-model="item.attributeValue"/>
              <el-date-picker :disabled = "isDisabled" v-else-if="item.attributeType === 4"
                              type="date"
                              value-format="YYYY-MM-DD"
                              style="width: 100%"
                              v-model="item.attributeValue"
              />
              <el-time-picker :disabled = "isDisabled" v-else-if="item.attributeType === 5" v-model="item.attributeValue"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="类型:" style="flex: 1; margin-right: 10px;">
              <el-text v-if="item.attributeType === 1" class="mx-1" type="info">文本</el-text>
              <el-text v-else-if="item.attributeType === 2" class="mx-1" type="info">数值</el-text>
              <el-text v-else-if="item.attributeType === 3" class="mx-1" type="info">小数</el-text>
              <el-text v-else-if="item.attributeType === 4" class="mx-1" type="info">日期</el-text>
              <el-text v-else-if="item.attributeType === 4" class="mx-1" type="info">时间</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="是否必填:" style="flex: 1; margin-right: 10px;">
              <el-text v-if="item.attributeRequired === 1" class="mx-1" type="danger">是</el-text>
              <el-text v-else-if="item.attributeRequired === 0" class="mx-1" type="info">否</el-text>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="提醒:" style="flex: 1; margin-right: 10px;">
              <el-text v-if="item.attributeRemind === 1" class="mx-1" type="danger">将提前{{item.attributeRemindAheadDay}}天提醒</el-text>
              <el-text v-else-if="item.attributeRemind === 0" class="mx-1" type="info">不提醒</el-text>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="合同扫描件" prop="upload" style="flex: 1; margin-right: 10px;">
              <el-upload :disabled = "isDisabled"
                  v-model:file-list="fileList"
                  :action="uploadAction"
                  :on-preview="handlePictureCardPreview"
                  list-type="picture-card"
              >
                <el-icon>
                  <Plus/>
                </el-icon>
                jpg/png/pdf
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="agreementDialogVisible = false">关闭</el-button>
          <el-button type="primary" v-if="!isDisabled" @click="addAgreement(agreementFormRef)">新增</el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog v-model="dialogVisible" width="80%">
      <div class="block">
        <el-image w-full :src="dialogImageUrl" />
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import {onMounted, ref} from "vue";
import UserBasic from "@/api/UserBasic.js";
import {useRoute, useRouter} from "vue-router";
import Agreement from "@/api/Agreement.js";
import base from "@/api/base.js";
import {Plus} from '@element-plus/icons-vue'
import SystemPost from "@/api/SystemPost.js";
import {ElMessage, ElMessageBox} from "element-plus";

const route = useRoute()
const router = useRouter()
const tableData = ref([]);
const tableLoading = ref(false)
const dialogLoading = ref(false)
const userLoading = ref(false)
const isDisabled = ref(false)
const agreementDialogVisible = ref(false)

const agreementFormRef = ref({})
const agreementValue = ref({
  userId: null,
  agreementTypeId: null,
  agreementName: null,
  agreementSignDate: null,
  agreementStartDate: null,
  agreementEndDate: null,
})

const agreementValueRules = ref({
  agreementTypeId: [
    {required: true, message: '请选择合同列別', trigger: 'blur' }
  ],
  agreementName: [
    {required: true, message: '请填写合同名称', trigger: 'blur' }
  ],
  agreementSignDate: [
    {type: 'date', required: true, message: '请选择签署时间', trigger: 'blur' }
  ],
  agreementStartDate: [
    {type: 'date', required: true, message: '请选择生效时间', trigger: 'blur' }
  ],
  agreementEndDate: [
    {type: 'date', required: true, message: '请选择失效时间', trigger: 'blur' }
  ],
})

const userInfoFormValue = ref({
  id: '',
  deptName: '',
  userName: '',
  userIdNumber: '',
  jobNumber: '',
  userSex: '',
  userCategory: '',
  highestEducation: '',
  graduationTime: ''
})

const uploadAction = `${base.context}/file/upload`
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const fileList = ref([])

const props = defineProps({
  userId: {
    type: String,
    required: true
  }
});


onMounted(() => {
  //获取详情
  getUserSimpleDetail()

  //获取合同列表
  listAllAgreement()
});

//获取用户简单详情
const getUserSimpleDetail = () => {
  let data = {};
  data.userId = props.userId
  userLoading.value = true
  UserBasic.getUserSimpleDetail(data)
      .then(res => {
        userInfoFormValue.value = res.data
        userLoading.value = false
      })
      .catch(error => {
        userLoading.value = false
      })
};

//获取合同列表
const listAllAgreement = () => {
  let data = {};
  data.userId = props.userId
  tableLoading.value = true
  Agreement.listAllAgreement(data)
      .then(res => {
        tableData.value = res.data
        tableLoading.value = false
      })
      .catch(error => {
        tableLoading.value = false
      })
};

const agreementTypeList = ref([]);
const agreementAttributeList = ref([]);
const handAdd = () => {
  isDisabled.value = false
  openAgreementDialog()
}
const openAgreementDialog = () => {
  agreementValue.value = {}
  agreementTypeList.value = [];
  agreementAttributeList.value = [];
  fileList.value = [];
  agreementDialogVisible.value = true
  dialogLoading.value = true
  Agreement.listAllAgreementType()
      .then(res => {
        agreementTypeList.value = res.data
        dialogLoading.value = false
      })
      .catch(error => {
        dialogLoading.value = false
      })
}
const agreementTypeChange = (attributeValueList) => {
  agreementAttributeList.value = [];
  if (agreementValue.value.agreementTypeId) {
    const body = ref({
      agreementTypeId: agreementValue.value.agreementTypeId
    })
    Agreement.queryAgreementAttribute(body.value)
        .then(res => {
          agreementAttributeList.value = res.data
          if (attributeValueList) {
            agreementAttributeList.value.forEach((item, index) => {
              for (let i = 0; i < attributeValueList.length; i++) {
                if (attributeValueList[i].attributeCode === item.attributeCode) {
                  item.attributeValue = attributeValueList[i].attributeValue
                  break
                }
              }
            })
          }
        })
  }
}

const addAgreement = (formEl) => {
  if (!formEl) return
  formEl.validate((valid, fields) => {
    if (valid) {
      let data = {};
      data.userId = props.userId
      data.agreementTypeId = agreementValue.value.agreementTypeId
      data.agreementName = agreementValue.value.agreementName
      data.agreementSignDate = agreementValue.value.agreementSignDate
      data.agreementStartDate = agreementValue.value.agreementStartDate
      data.agreementEndDate = agreementValue.value.agreementEndDate
      let attachFileIdList = []
      fileList.value.forEach((item, index) => {
        attachFileIdList.push(item.response.data.id)
      });
      data.attachFileIdList = attachFileIdList

      let attributeList = []
      agreementAttributeList.value.forEach((item, index) => {
        let o = {}
        o.attributeCode = item.attributeCode
        o.attributeValue = item.attributeValue
        attributeList.push(o)
      })
      data.agreementAttributeList = attributeList
      dialogLoading.value = true
      Agreement.addAgreement(data)
          .then(res => {
            dialogLoading.value = false
            agreementDialogVisible.value = false
            listAllAgreement()
          })
          .catch(error => {
            dialogLoading.value = false
          })
    } else {
      ElMessage.error('请检查必填项')
    }
  })
}
const handleDetail = (index, row) => {
  isDisabled.value = true
  let data = {};
  data.id = row.id
  Agreement.getAgreement(data)
      .then(res => {
        openAgreementDialog()
        agreementValue.value = res.data
        agreementValue.value.agreementTypeId = res.data.agreementTypeId
        agreementTypeChange(res.data.agreementAttributeList)

        fileList.value = [];
        res.data.attachFileVOList.forEach((item, index) => {
          const file = ref({
            name: item.fileSaveName,
            url: `${base.context}/file/get/image/` + item.fileSaveName,
            response:{
              data:{
                id:item.id
              }
            }
          })
          fileList.value.push(file.value)
        })
      })
      .catch(error => {
        dialogLoading.value = false
      })
}
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
      '数据将彻底删除，是否继续？',
      'Warning',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(() => {
        let data = {};
        data.id = row.id
        Agreement.deleteAgreement(data)
            .then(res => {
              ElMessage.success('删除成功')
              listAllAgreement()
            })
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '已取消',
        })
      })
}

const handlePictureCardPreview = (uploadFile) => {
  if (uploadFile.name && (uploadFile.name.endsWith("jpg") || uploadFile.name.endsWith("png"))) {
    dialogImageUrl.value = uploadFile.url
    dialogVisible.value = true
  } else {
    window.open(uploadFile.url, '_blank');
  }
};

</script>

<style scoped>
.form-inline {
  margin: 20px;
}

.form-inline .el-input {
  --el-input-width: 200px;
}

.form-inline .el-select {
  --el-select-width: 200px;
}

.block {
  padding: 10px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  display: inline-block;
  width: 100%;
  box-sizing: border-box;
  vertical-align: top;
}
.el-image {
  padding: 0 5px;
}
</style>